package com.zdy.im.tio.command.handler;

import com.github.houbb.sensitive.word.core.SensitiveWordHelper;
import com.sixeco.framework.common.api.ApiDoc;
import com.sixeco.framework.common.enums.TbStatusEnum;
import com.sixeco.framework.util.date.DateUtil;
import com.sixeco.framework.util.ids.GlobalId;
import com.sixeco.framework.util.json.JsonUtils;
import com.zdy.im.chat.ChatMessageEnum;
import com.zdy.im.chat.ChatMessageInfo;
import com.zdy.im.common.exception.ImException;
import com.zdy.im.core.ICommand;
import com.zdy.im.core.ImStatus;
import com.zdy.im.enums.ImMessageTypeEnum;
import com.zdy.im.tio.TioServerConfig;
import com.zdy.im.tio.command.AbstractCommandHandler;
import com.zdy.im.tio.command.Command;
import com.zdy.im.tio.command.ProtocolManager;
import com.zdy.im.tio.packets.JoinFriendRequestVo;
import com.zdy.im.user.dto.request.ImChatReadStatusRequestDto;
import com.zdy.im.user.dto.request.ImJoinFriendRequestDto;
import com.zdy.im.user.dto.request.ImJoinFriendStatusRequestDto;
import com.zdy.im.user.dto.response.ImJoinFriendResponseDto;
import com.zdy.im.user.service.ImJoinFriendService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.stereotype.Component;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.intf.Packet;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;

import javax.annotation.Resource;
import java.util.Date;


/**
 * 
 * 版本: [1.0]
 * 功能说明: 加入群组消息cmd命令处理器
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 */
@Component
@ApiDoc(module = "WebSocket 项目文档--加入群，绑定群关系",group = "SOCKET-GROUP")
public class JoinFriendReqHandler extends AbstractCommandHandler {

	private static Logger log = LoggerFactory.getLogger(JoinFriendReqHandler.class);


	@Autowired
	private ImJoinFriendService imJoinFriendService;

	@Resource
	private DefaultTokenServices defaultTokenServices;

	@Override
	public ICommand command() {

		return Command.COMMAND_JOIN_FRIEND_ACTION_REQ;
	}

	public ICommand responseCmd() {
		return Command.COMMAND_JOIN_FRIEND_ACTION_RESP;
	}

	@ApiDoc(
			cmd = "11",methodType = "ws",
			value = "申请加好友请求消息协议 cmd=11",
			request = JoinFriendRequestVo.class,
			response = ImChatReadStatusRequestDto.class
	)
	@Override
	public Packet handler(Packet wsPacket, ChannelContext channelContext) throws ImException{
		//绑定群组;
		WsRequest packet = (WsRequest) wsPacket;

		ChatMessageInfo sendInfo = converterWsParam(packet,channelContext);
		if(sendInfo == null){
			Packet errorPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext,responseCmd());
			return errorPacket;
		}
		ChatMessageEnum messageEnum = ChatMessageEnum.getEnum(sendInfo.getType());
		JoinFriendRequestVo vo = JsonUtils.parseJson(sendInfo.getExt(), JoinFriendRequestVo.class);
		if (null == messageEnum || vo == null || vo.getToId() <= 0 || vo.getToken() == null) {
			Packet respChatPacket = ProtocolManager.ResponsePacket.dataInCorrect(channelContext,responseCmd());
			return respChatPacket;
		}

//		OAuth2Authentication auth2Authentication = defaultTokenServices.loadAuthentication(vo.getToken());
//		User user = (User) auth2Authentication.getUserAuthentication().getPrincipal();
//		if(null == user){
//			throw new SystemRuntimeException(SysResultCodeEnum.SYS_USER_CODE_NOT);
//		}



		ImJoinFriendRequestDto joinFriend = ImJoinFriendRequestDto.build().clone(vo);
		//content 内容就是用户名称，多个有逗号分隔
		String content = SensitiveWordHelper.replace(vo.getReasons());
		joinFriend.setContent(joinFriend.getSendUserName()+"申请加为好友:原因"+content);
		joinFriend.setGlobalId(GlobalId.get().nextId());
		joinFriend.setJoinStatus(0);//未读
		joinFriend.setStatus(TbStatusEnum.ENABLE.index());
		joinFriend.setType(ImMessageTypeEnum.JOIN_FRIEND.getKey());

		ImJoinFriendStatusRequestDto joinFriendStatusDto = ImJoinFriendStatusRequestDto.build();
		joinFriendStatusDto.setSendUserId(joinFriend.getSendUserId());
		joinFriendStatusDto.setToId(joinFriend.getToId());
		ImJoinFriendResponseDto result = imJoinFriendService.getImJoinFriendByUserAndFriendId(joinFriendStatusDto);
		//0.未读 1.同意  2.拒绝,3.删除
		boolean isResult = true;
		if (null != result ){
			if(result.getJoinStatus() ==0){
				return ProtocolManager.ResponsePacket.dataToSendFailed(
						channelContext,responseCmd(), ImStatus.C10013);
			}
			if( result.getJoinStatus() ==1){
				return ProtocolManager.ResponsePacket.dataToSendFailed(
						channelContext,responseCmd(), ImStatus.C10015);
			}

			Date oneDate = DateUtil.addField(new Date(), DateUtil.DateEnum.DAYS ,-1);
			if (oneDate.after(result.getModifyDate() )&&
					(result.getJoinStatus() ==2 || result.getJoinStatus() ==3)){
				return ProtocolManager.ResponsePacket.dataToSendFailed(
						channelContext,responseCmd(), ImStatus.C10014);
			}
			//todo 修改记录
			joinFriend.setId(result.getId());
			joinFriend.setCreateDate(result.getCreateDate());
			joinFriend.setModifyDate(new Date());
			joinFriend.setGlobalId(result.getGlobalId());
			isResult = imJoinFriendService.updateImJoinFriend(joinFriend);
		}else {
			//todo 保存聊天记录;新增加记录
			result = imJoinFriendService.saveImJoinFriend(joinFriend);
		}


		if(null == result || !isResult){
			return ProtocolManager.ResponsePacket.dataToSendFailed(channelContext);
		}
		WsResponse wsResponse = WsResponse.fromText(JsonUtils.toJson(joinFriend), TioServerConfig.CHARSET);
		String toId = String.valueOf(joinFriend.getToId());
		Tio.sendToUser(channelContext.tioConfig,toId, wsResponse);
		return ProtocolManager.ResponsePacket.success(channelContext,responseCmd());

	}




}
